package com.dushibao.filter;

import com.dushibao.entity.User;
import com.dushibao.service.UserService;
import com.dushibao.service.impl.UserServiceImpl;
import com.dushibao.util.CommUtils;
import com.dushibao.util.ResultUtils;
import com.dushibao.util.SecurityHolder;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.List;

@WebFilter(filterName = "AuthorizationFilter",urlPatterns = "/*")
public class AuthorizationFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        req.setCharacterEncoding("UTF-8");
        res.setContentType("text/html;charset=UTF-8");

        /* 允许跨域的主机地址 */
        res.setHeader("Access-Control-Allow-Origin", "*");
        /* 允许跨域的请求方法GET, POST, HEAD 等 */
        res.setHeader("Access-Control-Allow-Methods", "*");
        /* 重新预检验跨域的缓存时间 (s) */
        res.setHeader("Access-Control-Max-Age", "4200");
        /* 允许跨域的请求头 */
        res.setHeader("Access-Control-Allow-Headers", "*");
        /* 是否携带cookie */
        res.setHeader("Access-Control-Allow-Credentials", "true");

        SecurityHolder.setContext(req,res);

        String servletPath = req.getServletPath();

        List<String> exts = Arrays.asList("css","js","jpg","png","login","register","ico","upload");

        //判断token
        String token = req.getHeader("token");

        //不拦截的请求:后缀是css、js、jpg、png,或者包含路径login、register的
        //如果携带token也可以直接访问
        if(CommUtils.endWith(exts,servletPath) || token!=null){
            chain.doFilter(request,response);
            return;
        }

        res.getWriter().write(ResultUtils.error("没有访问权限!"));

    }
}
